from io import BytesIO
import random

from PIL import Image, ImageDraw, ImageFont
from django.http import HttpResponse

# Create your views here.
from taotao import settings
from user_operation.utils import get_color, generate_code


def get_code(request):
    mode = "RGB"
    size = (200, 100)
    red = get_color()
    green = get_color()
    blue = get_color()
    color_bg = (red, green, blue)
    image = Image.new(mode=mode, size=size, color=color_bg)
    imagedraw = ImageDraw.ImageDraw(image, mode=mode)
    imagefont = ImageFont.truetype(settings.FONT_PATH, 70)
    verify_code = generate_code()
    request.session['verifycode'] = verify_code
    for i in range(4):
        fill = (get_color(), get_color(), get_color())
        imagedraw.text(xy=(50 * i, 0), text=verify_code[i], font=imagefont, fill=fill)

    for i in range(10000):
        fill = (get_color(), get_color(), get_color())
        xy = (random.randrange(201), random.randrange(100))
        imagedraw.point(xy=xy, fill=fill)

    fp = BytesIO()
    image.save(fp, "png")
    return HttpResponse(fp.getvalue(), content_type='image/png')
